package com.cyj.dream.core.util.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description: 年龄计算
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.util.date
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-26 13:29
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
public class AgeUtils {

    /**
     * 根据生日计算当前周岁数
     *
     * @param birthday
     * @return
     */
    public static int getCurrentAge(Date birthday) {
        // 当前时间
        Calendar curr = Calendar.getInstance();
        // 生日
        Calendar born = Calendar.getInstance();
        born.setTime(birthday);
        // 年龄 = 当前年 - 出生年
        int age = curr.get(Calendar.YEAR) - born.get(Calendar.YEAR);
        if (age <= 0) {
            return 0;
        }
        // 如果当前月份小于出生月份: age-1
        // 如果当前月份等于出生月份, 且当前日小于出生日: age-1
        int currMonth = curr.get(Calendar.MONTH);
        int currDay = curr.get(Calendar.DAY_OF_MONTH);
        int bornMonth = born.get(Calendar.MONTH);
        int bornDay = born.get(Calendar.DAY_OF_MONTH);
        if ((currMonth < bornMonth) || (currMonth == bornMonth && currDay <= bornDay)) {
            age--;
        }
        return age < 0 ? 0 : age;
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

        //时分秒
        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);

        String sBuffer = hour + ":" + minute + ":" + second;
        //将字符串转换为date类型
        Date dt1 = formatter.parse("1998-01-02 00:00:00");

        int age = AgeUtils.getCurrentAge(dt1);
        System.out.println("age======>" + age);
    }

}
